//
//  AddImageViewController.m
//  jiyujiaProgram
//
//  Created by Jame on 15/10/27.
//  Copyright © 2015年 中良 赵. All rights reserved.
//

#import "AddImageViewController.h"
#import "AddImageCell.h"

@interface AddImageViewController () <UITableViewDataSource,UITableViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic, copy) NSString *imageId;
@property (nonatomic, copy) NSString *imageUrl;

@end

@implementation AddImageViewController
{
    UITableView *_tableView;
    NSData *_imageData;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self creatNavigationBarWithImage:nil title:@"添加图片"];
    [self creatNavigationBarLeftItemWithLeftTitle:nil LeftImage:ECIMAGENAME(@"back_button.png")];
    
    [self creatTableView];
}

- (void)leftBtnClick:(id)leftSender
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)creatTableView
{
    self.automaticallyAdjustsScrollViewInsets = YES;
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(10, 64, ECSCREEN_W - 20, ECSCREEN_H - 64) style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = BG_COLOR;
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.scrollEnabled = NO;
    
    _tableView.tableFooterView = [[UIView alloc]init];//去掉多余的线
    if ([_tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        //让线头不留白
        [_tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([_tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [_tableView setLayoutMargins:UIEdgeInsetsZero];
    }
}


#pragma mark - tableViewHeightForRowAtIndexPath
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section;
{
    return 5;
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ECSCREEN_W, 5)];
    view.backgroundColor = BG_COLOR;
    return view;
}


#pragma mark - tableViewNumberOfRowsInSection
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}


#pragma mark - tableViewCellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *reuseIdentifier = @"addImageCell";
    AddImageCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (nil == cell) {
        NSArray *arr = [[NSBundle mainBundle]loadNibNamed:@"AddImageCell" owner:nil options:nil];
        for (NSObject *obj in arr) {
            if ([obj isKindOfClass:[AddImageCell class]]) {
                cell = (AddImageCell *)obj;
                if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
                    [cell setSeparatorInset:UIEdgeInsetsZero];
                }
                if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
                    [cell setLayoutMargins:UIEdgeInsetsZero];
                }
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                break;
            }
        }
    }
    
    cell.clipsToBounds = YES;
    cell.layer.cornerRadius = 3;
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    [cell setCellWithIndexPath:indexPath];
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 0:
        {
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
            {
                UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                picker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
                picker.delegate = self;
                picker.allowsEditing = YES;
                picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                [self presentViewController:picker animated:YES completion:nil];
            }
        }
            break;
        case 1:
        {
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
            {
                UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                picker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
                picker.delegate = self;
                picker.allowsEditing = YES;
                picker.sourceType = UIImagePickerControllerSourceTypeCamera;
                [self presentViewController:picker animated:YES completion:nil];
            }

        }
            break;

            
        default:
            break;
    }
}



- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
    
    dispatch_async(queue, ^{
        
        if (picker.sourceType == UIImagePickerControllerSourceTypeCamera)
        {
            UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
        }
        
        if (UIImagePNGRepresentation(image))
        {
            UIImage *newImage = [ECHelper imageWithImageSimple:image scaledToSize:CGSizeMake(320.0f, 320.0f)];
            _imageData = UIImagePNGRepresentation(newImage);
        }
        else
        {
            UIImage *newImage = [ECHelper imageWithImageSimple:image scaledToSize:CGSizeMake(320.0f, 320.0f)];
            _imageData = UIImageJPEGRepresentation(newImage, 0.75);
        }
        
    });
    
#warning ******************POSTPIC********************
    [self dismissViewControllerAnimated:YES completion:^{
        
        NSString *strRandomName = [NSString stringWithFormat:@"iOS_uploadImage_%d.jpg",arc4random_uniform(10000)];
        
        NSArray *files = @[
                           @{
                               @"name": strRandomName,
                               @"file": _imageData ,
                               @"key": @"image",
                               @"type": @"multipart/form-data"
                               }
                           ];
        
        [[HttpManager defaultManager] uploadToUrl:RequestURL(POSTPIC) params:nil files:files complete:^(BOOL successed, NSDictionary *result) {
            if (successed) {
                if ([result[@"errCode"] integerValue] == 0) {
//                    self.imageId = result[@"pictures_ID"];
//                    self.imageUrl = result[@"path"];
                    [self.navigationController popViewControllerAnimated:YES];
                    if (self.addImage) {
                        self.addImage(result[@"pictures_ID"],result[@"path"],_imageData);
                    }
                }else{
                    SHOW_ALERT(@"提示", result[@"errMsg"], @"好的", nil, nil);
                }
            }
        }];
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
